package cn.com.nxt.txb.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nim.uikit.common.util.sys.NetworkUtil;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.constant.AVChatType;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.com.nxt.txb.R;
import cn.com.nxt.txb.SampleApplicationLike;
import cn.com.nxt.txb.TextureVideoActivity;
import cn.com.nxt.txb.adapter.BusinessNumberAdapter;
import cn.com.nxt.txb.avchat.activity.AVChatActivity;
import cn.com.nxt.txb.education.activity.ChatRoomActivity;
import cn.com.nxt.txb.httpdelegate.BusinessDelegate;
import cn.com.nxt.txb.httpdelegate.LiveDelegate;
import cn.com.nxt.txb.httpdelegate.MeetingDelegate;
import cn.com.nxt.txb.model.BusinessNumber;
import cn.com.nxt.txb.model.CallRecord;
import cn.com.nxt.txb.util.AppUtil;
import cn.com.nxt.txb.util.MyItemDecoration;
import cn.com.nxt.txb.util.OnRecyclerItemClickListener;

/**
 * Created by xuejinwei on 2016/11/11.
 * Email:xuejinwei@outlook.com
 */
@ContentView(R.layout.fragment_business)
public class BusinessFragment extends BaseFragment {
    private View loadingView;
    private View failureView;
    private View businessCloseView;
    @ViewInject(R.id.fl_content)
    private FrameLayout mFlContent;
    private static boolean isFirst = true;
    private BusinessDelegate businessDelegate;
    private MeetingDelegate meetingDelegate;
    private LiveDelegate liveDelegate;
    private byte BUSINESS_INFO_FLAG = 0x00;
    private byte BUSINESS_NUMBER_LIST_FLAG = 0x01;
    private final byte IS_MEETING_BEGIN = 0x30;
    private final byte MEETING_IN_AUTH = 0x31;
    private final byte MEETING_IN_CHECK = 0x32;
    private final byte LIVE_ADDRESS = 0x33;
    private final byte LIVE_PUBLISH = 0x34;
    private BusinessNumberAdapter mAdapter;
    private List<BusinessNumber> list;
    @ViewInject(R.id.rv)
    private RecyclerView rv;
    private boolean isLazyLoad=false;
    public static String name;
    public static String roomid;
    public static String meetingid;
    public static int status;
    public static String data;
    private static final int PERMISSION_REQUEST_CODE = 10;
    private BusinessNumber currentNumber;

    public static BusinessFragment newInstance(String info) {
        Bundle args = new Bundle();
        BusinessFragment fragment = new BusinessFragment();
        args.putString("info", info);
        fragment.setArguments(args);
        return fragment;
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        if(!isVisibleToUser)
//            return;
//        if (getUserVisibleHint() && isFirst) {
//            if(mFlContent==null){
//                isLazyLoad=true;
//                return;
//            }
//            loadData();
//        }
//    }

    private void loadData() {
        if (SampleApplicationLike.isNotBusniessUser) {
            mFlContent.addView(businessCloseView);
            isFirst=false;
            return;
        }
        mFlContent.addView(loadingView);
        if (TextUtils.isEmpty(SampleApplicationLike.businessName) || TextUtils.isEmpty(SampleApplicationLike.businessID)) {
            businessDelegate.businessInfo(AppUtil.mUser.getToken(), BUSINESS_INFO_FLAG);
        } else {
            businessDelegate.getBusinessNumberList(SampleApplicationLike.businessID, AppUtil.mUser.getToken(), BUSINESS_NUMBER_LIST_FLAG);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        loadingView = inflater.inflate(R.layout.loading, null);
        failureView = inflater.inflate(R.layout.load_failure, null);
        businessCloseView = inflater.inflate(R.layout.business_close, null);
        businessDelegate = new BusinessDelegate(this);
        rv.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv.addItemDecoration(new MyItemDecoration());
//        if(isLazyLoad){
//            isLazyLoad=false;
//            loadData();
//        }
        loadData();
        return view;
    }

    @Override
    public void success(String result, byte flag) {
        super.success(result, flag);
        disDialog();
        if (flag == BUSINESS_INFO_FLAG)
            businessInfo(result);
        else if (flag == BUSINESS_NUMBER_LIST_FLAG)
            businessNumberList(result);
        else if (flag == IS_MEETING_BEGIN)
            isMeetingBeginSuccess(result);
        else if (flag == MEETING_IN_AUTH)
            meetingInAuthSuccess(result);
        else if (flag == MEETING_IN_CHECK)
            getLiveAddress();
        else if (flag == LIVE_ADDRESS)
            startLive(result);
        else if(flag==LIVE_PUBLISH)
            livePublishSuccess(result);
    }

    private void livePublishSuccess(String result){
        disDialog();
        data=result;
        meeting();
    }

    private void businessNumberList(String result) {
        mFlContent.removeView(loadingView);
        try {
            list = new ArrayList<>();
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                Gson gson = new Gson();
                BusinessNumber number = gson.fromJson(array.getString(i), BusinessNumber.class);
                list.add(number);
            }
            mAdapter = new BusinessNumberAdapter(getActivity(), list);
            mAdapter.setOnItemClickListener(mOnItemClickListener);
            rv.setAdapter(mAdapter);
            isFirst=false;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void businessInfo(String result) {
        JSONObject obj = null;
        try {
            obj = new JSONObject(result);
            SampleApplicationLike.businessName = obj.optString("name");
            SampleApplicationLike.businessID = obj.optString("bsid");
            businessDelegate.getBusinessNumberList(SampleApplicationLike.businessID, AppUtil.mUser.getToken(), BUSINESS_NUMBER_LIST_FLAG);
        } catch (JSONException e) {
        }
    }

    private OnRecyclerItemClickListener mOnItemClickListener = new OnRecyclerItemClickListener() {
        @Override
        public void OnItemClick(View v, int pos) {
            currentNumber=list.get(pos);
            if (currentNumber.getPhone().startsWith("1")) {
                if (currentNumber.getPhone().equals(AppUtil.mUser.getPhone())) {
                    showToast("不能呼叫自己！");
                    return;
                }
                startAudioVideoCall(AVChatType.AUDIO, currentNumber.getPhone(),currentNumber.getName());
            } else if (currentNumber.getPhone().startsWith("81")) {
                startMeeting(currentNumber.getPhone());
            }
        }
    };

    public void startAudioVideoCall(AVChatType avChatType, String account,String name) {
        AVChatActivity.launch(getActivity(), account, avChatType.getValue(), AVChatActivity.FROM_INTERNAL,name);
    }

    private void startMeeting(String roomId) {
        showDialog("正在检测会议是否开始");
        meetingDelegate.isMeetingBegin(AppUtil.mUser.getToken(), roomId, IS_MEETING_BEGIN);
    }
    private void isMeetingBeginSuccess(String result) {
        try {
            JSONObject obj = new JSONObject(result);
            name = obj.optString("name");
            roomid = obj.optString("roomid");
            meetingid = obj.optString("meetingid");
            status = obj.optInt("status");
            if (status == 11&&roomid.equals(AppUtil.mUser.getRommid())){
                showDialog();
                liveDelegate.livePublish(roomid,LIVE_PUBLISH);
            }else if (status == 2)
                joinMeeting(roomid);
        } catch (JSONException e) {
        }
    }

    private void meeting() {
        if (!NetworkUtil.isNetAvailable(getActivity())) {
            showToast(R.string.network_is_not_available);
            return;
        }
        if (checkPermission()) {
            createOrEnterRoom();
        } else {
            requestPermissions();
        }
    }

    private void joinMeeting(String roomid) {
        showDialog("正在验证入会权限");
        meetingDelegate.meetingInAuth(AppUtil.mUser.getToken(), roomid, MEETING_IN_AUTH);
    }
    //检查所有的权限
    private boolean checkPermission() {
        final List<String> missed = AVChatManager.checkPermission(getActivity());
        if (missed.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (AVChatManager.checkPermission(getActivity()).size() == 0) {
                    createOrEnterRoom();
                } else {
                    showToast("无权限");
                    // Toast.makeText(this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                    //       .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    private void createOrEnterRoom() {
        DialogMaker.showProgressDialog(getActivity(), "", false);
        createChannel(roomid);
    }

    /**
     * 创建会议频道
     */

    private void createChannel(final String roomId) {
        AVChatManager.getInstance().createRoom(roomId, "avchat test", new AVChatCallback<AVChatChannelInfo>() {
            @Override
            public void onSuccess(AVChatChannelInfo avChatChannelInfo) {
                DialogMaker.dismissProgressDialog();
                ChatRoomActivity.start(getActivity(), roomId,meetingid, true, false, data);
                // finish();
            }

            @Override
            public void onFailed(int i) {
                DialogMaker.dismissProgressDialog();
                if (i == 417) {
                    ChatRoomActivity.start(getActivity(), roomid,meetingid, true, false, data);
                    return;
                }
                //关闭视频预览
                //AVChatManager.getInstance().stopVideoPreview();
//离开房间
                AVChatManager.getInstance().leaveRoom2(roomid, new AVChatCallback<Void>() {

                    @Override
                    public void onSuccess(Void aVoid) {

                    }

                    @Override
                    public void onFailed(int i) {

                    }

                    @Override
                    public void onException(Throwable throwable) {

                    }
                });
//关闭音视频引擎
                // AVChatManager.getInstance().disableRtc();
                showToast("创建频道失败, code:" + i);
            }

            @Override
            public void onException(Throwable throwable) {
                DialogMaker.dismissProgressDialog();
            }
        });
    }

    private void requestPermissions() {
        final List<String> missed = AVChatManager.checkPermission(getActivity());
        List<String> showRationale = new ArrayList<>();
        for (String permission : missed) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
                showRationale.add(permission);
            }
        }

        if (showRationale.size() > 0) {
            new AlertDialog.Builder(getActivity())
                    .setMessage("You need to allow some permission")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(getActivity(), missed.toArray(new String[missed.size()]),
                                    PERMISSION_REQUEST_CODE);
                        }
                    })
                    .setNegativeButton("Cancel", null)
                    .create()
                    .show();
        } else {
            ActivityCompat.requestPermissions(getActivity(), missed.toArray(new String[missed.size()]), PERMISSION_REQUEST_CODE);
        }
    }

    private void startLive(String result) {
        Intent intent = new Intent(getActivity(), TextureVideoActivity.class);
        intent.putExtra("roomid", currentNumber.getPhone());
        intent.putExtra("meetingid", meetingid);
        intent.putExtra("path", "rtmp://" + result + ":1935/txb/" + currentNumber.getPhone());
        startActivity(intent);
    }

    private void meetingInAuthSuccess(String result) {
        try {
            JSONObject obj = new JSONObject(result);
            int auth = obj.optInt("auth");
            if (auth == 0)
                checkMeetingPassword();
            else if (auth == 1)
                getLiveAddress();//有权限，直接获取
        } catch (JSONException e) {
        }
    }

    private void checkMeetingPassword() {
        final EditText et = new EditText(getActivity());
        et.setHint("请输入入会密码");
        new AlertDialog.Builder(getActivity()).setTitle("搜索")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        String input = et.getText().toString();
                        showToast("正在验证入会密码");
                        meetingDelegate.meetingInCheck(AppUtil.mUser.getToken(), input, MEETING_IN_CHECK);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void getLiveAddress() {
        showDialog("正在进入房间");
        liveDelegate.liveAddress(LIVE_ADDRESS);
    }
}
